package com.dht.xiao.jianye.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.dht.xiao.jianye.R;
import com.dht.xiao.jianye.adapter.OpenDoorAdapter;
import com.dht.xiao.jianye.adapter.RecyclerAdapter;
import com.dht.xiao.jianye.adapter.SelectAdapter;
import com.dht.xiao.jianye.base.BaseActivity;
import com.dht.xiao.jianye.utils.ByteUtil;
import com.dht.xiao.jianye.utils.LogToFile;
import com.dht.xiao.jianye.utils.SerialPortUtil;
import com.licheedev.myutils.LogPlus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class OpenDoorActivity extends BaseActivity {
    @BindView(R.id.send)
    TextView send;
    @BindView(R.id.recycler_customer)
    RecyclerView mRecyclerView;

    private SelectAdapter mOpenDoorAdapter;
    private SerialPortUtil portUtil;

    private String box_id = "";
    private Handler mHandler = new Handler();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_open_door;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        initRecyclerView();
        initPort();
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mOpenDoorAdapter = new SelectAdapter();
        mRecyclerView.setAdapter(mOpenDoorAdapter);
        List<String> datalist = new ArrayList<>();
        for (int i = 0; i < 30;i++){
            datalist.add((i+1)+"");
        }
        mOpenDoorAdapter.setNewData(datalist);

        mOpenDoorAdapter.setOnItemClickListener(new SelectAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, String data, int position) {

            }
        });
    }
    @OnClick(R.id.btn_read)
    public void onViewClicked() {
    }

    private void initPort() {
        try {
            portUtil = SerialPortUtil.getInstance(mHandler);
            portUtil.setCallBack(new SerialPortUtil.OperationResult() {
                @Override
                public void receiveResult(String command, byte[] allData) {
                    final String string = ByteUtil.bytes2HexStr(allData);
                    if (string.length() < 8) {
                        return;
                    }
                    LogToFile.e("获取到了可以处理的命令="+string);
                    if (command.equals("82")) {//开锁
                        LogPlus.e("MainActivity接收到的==", string);
                        String status = string.substring(string.length() - 4, string.length() - 2);
                        int door_number = Integer.parseInt(
                                string.substring(string.length() - 6, string.length() - 4), 16);
                        if (status.equals("00")) {//开启
                            star_inquire(Integer.parseInt(box_id));
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        if (!OpenDoorActivity.this.isFinishing()) {
                                            showToast("门开启成功，正在查询等待门关闭");
                                        }
                                    }catch (Exception e){

                                    }

                                }
                            });
                        }
                    } else if (command.equals("83")) {//查询锁状态
                        //  574B4C590B018300030182
                        String status = string.substring(string.length() - 4, string.length() - 2);
                        LogPlus.e("状态status="+status);
                        int door_number = Integer.parseInt(
                                string.substring(string.length() - 6, string.length() - 4), 16);
                        if (status.equals("00")) {//开启

                        } else {
                            LogPlus.e("执行状态status="+status);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!OpenDoorActivity.this.isFinishing()) {
                                        showOneToast("锁关闭了");
                                        showWaitingDialog("请稍后正在读取", false);
                                    }
                                }
                            });
                            if (mObservable != null){
                                mObservable.dispose();
                                mObservable = null;
                            }
                        }
                    }
                }
            });
        } catch (Exception e) {

        }

    }

    private Disposable mObservable;
    private void star_inquire(final int num) {
        if (mObservable != null){
            mObservable.dispose();
            mObservable = null;
        }
        mObservable = Observable.interval(2,2, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (portUtil != null) {
                            portUtil.inquire_door(num);
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mObservable != null){
            mObservable.dispose();
            mObservable = null;
        }
        if (portUtil != null){
            portUtil = null;
        }
    }
}
